#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
服务器数据上报模块
用于向服务器上报车牌识别结果和设备心跳
"""

import requests
import json
import time
import yaml
import os


class DataUploader:
    """数据上报器"""
    
    def __init__(self):
        """
        初始化数据上报器
        """
        self.car_info_api_url = "http://njapi.wenfree.cn/?s=App.Aky_CarInfo.Add"
        self.heartbeat_api_url = "http://njapi.wenfree.cn/?s=App.Aky_VideoList.Heartbeat"
        self.device_name = self._get_device_name()
        
    def _get_device_name(self):
        """
        获取设备名称
        
        Returns:
            str: 设备名称
        """
        try:
            # 读取app.yaml文件获取设备名称
            yaml_path = os.path.join(os.path.dirname(__file__), "app.yaml")
            if os.path.exists(yaml_path):
                with open(yaml_path, 'r', encoding='utf-8') as f:
                    config = yaml.safe_load(f)
                    return config.get('name', '未知设备')
            else:
                return '未知设备'
        except Exception as e:
            print(f"获取设备名称失败: {str(e)}")
            return '未知设备'
        
    def upload_car_info(self, data):
        """
        上报车辆信息到服务器
        
        Args:
            data (dict): 包含车辆信息的字典
                必需字段:
                    category (str): 车辆类别
                    carNo (str): 车牌号码
                    pimg (str): 车牌图片URL
                    carimg (str): 场景图片URL
                可选字段:
                    vehicleNo (str): 车辆识别号
                    
        Returns:
            dict: 上报结果
                成功: {"success": True, "data": 响应数据}
                失败: {"success": False, "error": "错误信息"}
        """
        # 参数验证
        required_fields = ["category", "carNo", "pimg", "carimg"]
        for field in required_fields:
            if field not in data or not data[field]:
                return {
                    "success": False,
                    "error": f"缺少必需参数: {field}"
                }
        
        try:
            # 发送POST请求
            headers = {
                'Content-Type': 'application/json'
            }
            
            response = requests.post(
                self.car_info_api_url, 
                data=json.dumps(data), 
                headers=headers, 
                timeout=30
            )
            
            # 检查响应状态
            if response.status_code == 200:
                try:
                    result = response.json()
                    return {
                        "success": True,
                        "data": result
                    }
                except json.JSONDecodeError:
                    return {
                        "success": False,
                        "error": f"响应不是有效的JSON格式: {response.text}"
                    }
            else:
                return {
                    "success": False,
                    "error": f"HTTP请求失败，状态码: {response.status_code}, 响应: {response.text}"
                }
                
        except requests.exceptions.Timeout:
            return {
                "success": False,
                "error": "请求超时"
            }
        except requests.exceptions.ConnectionError:
            return {
                "success": False,
                "error": "网络连接错误"
            }
        except Exception as e:
            return {
                "success": False,
                "error": f"上报过程中出现异常: {str(e)}"
            }
            
    def send_heartbeat(self):
        """
        发送心跳到服务器
        
        Returns:
            dict: 心跳发送结果
                成功: {"success": True, "data": 响应数据}
                失败: {"success": False, "error": "错误信息"}
        """
        try:
            # 构造心跳数据
            data = {
                "name": self.device_name
            }
            
            # 发送POST请求
            headers = {
                'Content-Type': 'application/json'
            }
            
            response = requests.post(
                self.heartbeat_api_url, 
                data=json.dumps(data), 
                headers=headers, 
                timeout=30
            )
            
            # 检查响应状态
            if response.status_code == 200:
                try:
                    result = response.json()
                    print(f"心跳发送成功: {self.device_name}")
                    return {
                        "success": True,
                        "data": result
                    }
                except json.JSONDecodeError:
                    return {
                        "success": False,
                        "error": f"响应不是有效的JSON格式: {response.text}"
                    }
            else:
                return {
                    "success": False,
                    "error": f"HTTP请求失败，状态码: {response.status_code}, 响应: {response.text}"
                }
                
        except requests.exceptions.Timeout:
            return {
                "success": False,
                "error": "心跳请求超时"
            }
        except requests.exceptions.ConnectionError:
            return {
                "success": False,
                "error": "网络连接错误"
            }
        except Exception as e:
            return {
                "success": False,
                "error": f"发送心跳过程中出现异常: {str(e)}"
            }


def example():
    """使用示例"""
    # 创建数据上报器实例
    uploader = DataUploader()
    
    # 构造数据
    data = {
        "category": "泥头车",
        "carNo": "粤B12345",
        "pimg": "http://hongkongidcard.wenfree.cn/aky/2025/10/20/14+粤B12345.jpg",
        "carimg": "http://hongkongidcard.wenfree.cn/aky/2025/10/20/14+scene_粤B12345.jpg",
        "vehicleNo": "LD123456"
    }
    
    # 上报车辆信息
    result = uploader.upload_car_info(data)
    
    if result["success"]:
        print("数据上报成功:", result["data"])
    else:
        print("数据上报失败:", result["error"])
        
    # 发送心跳
    heartbeat_result = uploader.send_heartbeat()
    
    if heartbeat_result["success"]:
        print("心跳发送成功:", heartbeat_result["data"])
    else:
        print("心跳发送失败:", heartbeat_result["error"])


if __name__ == "__main__":
    example()